//
//  SWTool.m
//  Lightthings
//
//  Created by Hero on 2024/8/29.
//

#import "SWTool.h"
#define kStringFormat(...) [NSString stringWithFormat:__VA_ARGS__]
#define klSafeParameter(parameter) ((!parameter || parameter == (id)kCFNull) ? @"" : (parameter))
#define klSafeParameterSpace(parameter) ((!parameter || parameter == (id)kCFNull) ? @" " : (parameter))
@implementation SWTool
#pragma mark - 判空
+ (BOOL)objectIsNullAndEmpty:(NSObject *)object {
    if ([object isKindOfClass:[NSString class]]) {
        NSString *string = (NSString *)object;
        string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
        if ([string isEqual:@""]) {
            return YES;
        }
    }else if ([object isEqual:[NSNull null]] ||
              object == nil) {
        return YES;
    }
    return NO;
}

+ (BOOL)validatePassword:(NSString *)password {
    if(password.length == 0){
       return NO;
    }
    // 必须字母+数字
    NSString *regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{8,}$";
    NSPredicate *passwordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [passwordPredicate evaluateWithObject:password];
}

#pragma mark - 字符串辅助性工具
+ (NSMutableAttributedString *)attS1:(NSString *)str1
                                  s2:(NSString *)str2
                                  s3:(NSString *)str3
                                  f1:(UIFont * __nullable)f1
                                  c1:(UIColor * __nullable)c1
                                  f2:(UIFont * __nullable)f2
                                  c2:(UIColor * __nullable)c2
                                  f3:(UIFont * __nullable)f3
                                  c3:(UIColor * __nullable)c3 {
    if (str1 && str2 && str3) {
        NSString *allString = [NSString stringWithFormat:@"%@%@%@",str1,str2,str3];
        NSRange range1 = [allString rangeOfString:str1];
        NSRange range2 = [allString rangeOfString:str2];
        NSRange range3 = [allString rangeOfString:str3];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:allString];
        NSDictionary *dict1 = [self attributesF:f1 c:c1];
        NSDictionary *dict2 = [self attributesF:f2 c:c2];
        NSDictionary *dict3 = [self attributesF:f3 c:c3];
        if (dict1) [string addAttributes:dict1 range:range1];
        if (dict2) [string addAttributes:dict2 range:range2];
        if (dict3) [string addAttributes:dict3 range:range3];
        return string;
    }
    return nil;
}

+ (NSMutableAttributedString *)attS1:(NSString *)str1
                                  s2:(NSString *)str2
                                  f1:(UIFont *)f1
                                  c1:(UIColor *)c1
                                  f2:(UIFont *)f2
                                  c2:(UIColor *)c2 {
    if (str1 && str2) {
        NSString *allString = [NSString stringWithFormat:@"%@%@",str1,str2];
        NSRange range1 = [allString rangeOfString:str1];
        NSRange range2 = [allString rangeOfString:str2];
        NSDictionary *dict1 = [self attributesF:f1 c:c1];
        NSDictionary *dict2 = [self attributesF:f2 c:c2];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:allString];
        if (dict1) [string addAttributes:dict1 range:range1];
        if (dict2) [string addAttributes:dict2 range:range2];
        return string;
    }
    return nil;
}

+ (NSMutableAttributedString *)attS:(NSString *)str
                                  f:(UIFont *)f
                                  c:(UIColor *)c {
    if (str) {
        NSDictionary *dict = [self attributesF:f c:c];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str attributes:dict];
        return string;
    }
    return nil;
}

+ (NSMutableAttributedString *)attS:(NSString *)str
                                  f:(UIFont *)f
                                  c:(UIColor *)c
                                  h:(CGFloat)h {
    if (str) {
        NSDictionary *dict = [self attributesF:f c:c h:h];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str attributes:dict];
        return string;
    }
    return nil;
}

+ (NSMutableAttributedString *)attStrikeS1:(NSString *)str1
                                        s2:(NSString *)str2
                                        f1:(UIFont *)f1
                                        c1:(UIColor *)c1
                                        f2:(UIFont *)f2
                                        c2:(UIColor *)c2
                                        is:(BOOL)isFirst {
    if (str1 && str2) {
        NSString *allString = [NSString stringWithFormat:@"%@%@",str1,str2];
        NSRange range1 = [allString rangeOfString:str1];
        NSRange range2 = [allString rangeOfString:str2];
        NSDictionary *dict1 = [self attributesF:f1 c:c1];
        NSDictionary *dict2 = [self attributesF:f2 c:c2];
        if (isFirst) {
            NSMutableDictionary *d1 = [[NSMutableDictionary alloc] initWithDictionary:dict1];
            d1[NSStrikethroughStyleAttributeName] = [NSNumber numberWithInteger:NSUnderlineStyleSingle];
            dict1 = d1;
        }else {
            NSMutableDictionary *d2 = [[NSMutableDictionary alloc] initWithDictionary:dict2];
            d2[NSStrikethroughStyleAttributeName] = [NSNumber numberWithInteger:NSUnderlineStyleSingle];
            dict2 = d2;
        }
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:allString];
        if (dict1) [string addAttributes:dict1 range:range1];
        if (dict2) [string addAttributes:dict2 range:range2];
        return string;
    }
    return nil;
}

// 加中划线
+ (NSMutableAttributedString *)attStrikeS:(NSString *)str
                                        f:(UIFont * __nullable)f
                                        c:(UIColor * __nullable)c {
    if (str) {
        NSDictionary *dict = [self attributesF:f c:c];
        NSMutableDictionary *d1 = [[NSMutableDictionary alloc] initWithDictionary:dict];
        d1[NSStrikethroughStyleAttributeName] = [NSNumber numberWithInteger:NSUnderlineStyleSingle];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str attributes:d1];
        return string;
    }
    return nil;
}

// 下划线
+ (NSMutableAttributedString *)attUnderS:(NSString *)str
                                       f:(UIFont * __nullable)f
                                       c:(UIColor * __nullable)c {
    if (str) {
        NSDictionary *dict = [self attributesF:f c:c];
        NSMutableDictionary *d = [[NSMutableDictionary alloc] initWithDictionary:dict];
        d[NSUnderlineStyleAttributeName] = [NSNumber numberWithInteger:NSUnderlineStyleSingle];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str attributes:d];
        return string;
    }
    return nil;
}

+ (NSMutableAttributedString *)attUnderS:(NSString *)str1
                                      s2:(NSString *)str2
                                      s3:(NSString *)str3
                                      f1:(UIFont * __nullable)f1
                                      c1:(UIColor * __nullable)c1
                                      f2:(UIFont * __nullable)f2
                                      c2:(UIColor * __nullable)c2
                                      f3:(UIFont * __nullable)f3
                                      c3:(UIColor * __nullable)c3
                                      lc:(UIColor *)lc {
    if (str1 && str2 && str3) {
        NSString *allString = kStringFormat(@"%@%@%@",str1,str2,str3);
        NSRange range1 = [allString rangeOfString:str1];
        NSRange range2 = [allString rangeOfString:str2];
        NSRange range3 = [allString rangeOfString:str3];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:allString];
        NSMutableDictionary *d = [[NSMutableDictionary alloc] init];
        d[NSUnderlineStyleAttributeName] = [NSNumber numberWithInteger:NSUnderlineStyleSingle];
        if (lc) d[NSUnderlineColorAttributeName] = lc;
        [string addAttributes:d range:NSMakeRange(0, allString.length)];
        NSDictionary *dict1 = [self attributesF:f1 c:c1];
        NSDictionary *dict2 = [self attributesF:f2 c:c2];
        NSDictionary *dict3 = [self attributesF:f3 c:c3];
        if (dict1) [string addAttributes:dict1 range:range1];
        if (dict2) [string addAttributes:dict2 range:range2];
        if (dict3) [string addAttributes:dict3 range:range3];
        return string;
    }
    return nil;
}

+ (NSDictionary *)attributesF:(UIFont *)f c:(UIColor *)c {
    NSMutableDictionary *dict = [NSMutableDictionary new];
    if (f) {
        dict[NSFontAttributeName] = f;
    }
    if (c) {
        dict[NSForegroundColorAttributeName] = c;
    }
    return dict;
}

+ (NSDictionary *)attributesF:(UIFont *)f c:(UIColor *)c h:(CGFloat)h {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:[self attributesF:f c:c]];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = h;
//    [style setLineBreakMode:NSLineBreakByTruncatingTail]; // 需要去掉，因为设置这个属性的话，计算高度就会错误
    dict[NSParagraphStyleAttributeName] = style;
    return dict;
}

+ (NSAttributedString *)createTextAttibute:(NSString *)string dict:(NSDictionary *)dict {
    return [[NSAttributedString alloc] initWithString:klSafeParameter(string) attributes:dict];
}

+ (NSString *)limitMax:(NSInteger)max string:(NSString *)string {
    if (string && [string isKindOfClass:NSString.class]) {
        if (string.length > max) {
            NSString *sub = [string substringToIndex:max];
            return kStringFormat(@"%@...",sub);
        }
        return string;
    }
    return nil;
}

#pragma mark - 数字显示
/**
 小数浮点数转化成字符串
 @param num 浮点数
 @param min 最小小数位数
 @param max 最大小数位数
 */
+ (NSString *)strWithFloat:(double)num min:(NSInteger)min max:(NSInteger)max {
    if (num > 100000000) {
        return kStringFormat(@"%@",@(num));
    }else {
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    //    numberFormatter.numberStyle = kCFNumberFormatterNoStyle;
        //整数最少位数
        numberFormatter.minimumIntegerDigits = 1;
        //小数位最多位数
        numberFormatter.maximumFractionDigits = max;
        //小数位最少位数
        numberFormatter.minimumFractionDigits = 0;
        NSString *newAmount = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:num]];
        return newAmount;
    }
}

+ (BOOL)checkEmptyString:(NSString *)string {
    BOOL empty = (string.length < 1 || string == nil  || [string isEqualToString:@"(null)"] || [string isEqualToString:@"<null>"] || [string isEqualToString:@"null"] || [string isKindOfClass:[NSNull class]]);
    return empty ;
}


+ (NSData*)compressImageQuality:(UIImage*)image toByte:(NSInteger)maxLength {
    
    //先压缩size,再压缩质量
    UIImage *newimage = [self thumbnailWithKeepScale:image size:CGSizeMake(1000, 1000)];
    NSData *data = UIImageJPEGRepresentation(newimage, 1.0);
    if (data.length > maxLength*1024) {
        UIImage  *image1 = [self compressImage:newimage toByte:maxLength];
        NSData *data = UIImageJPEGRepresentation(image1, 1.0);
        return data;
    }else {
        return data;
    }
}

//根据最新的size，保持原图的宽高比，生成一个缩略图
+ (UIImage *)thumbnailWithKeepScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = 0;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = 0;
        }
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, rect.size.width, rect.size.height));
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}

//p>循环压缩图片质量</p>
+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 3; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    NSUInteger temLength = 0;
    while (data.length > maxLength && data.length != temLength) {
        temLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, 600, 600)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}

+ (void)showAlertTitle:(NSString *)title Message:(NSString *)message CancelTitle:(NSString *)cancelTitle CancelAction:(void (^)(void))cancelAction SureTitle:(NSString *)sureTitle SureAction:(void (^)(void))sureAction {
    if (cancelTitle && sureTitle) {
        LEEAlert.alert.config
        .LeeTitle(title)
        .LeeContent(message)
        .LeeMaxWidth(280)
        .LeeAddAction(^(LEEAction * _Nonnull action) {
            action.title = cancelTitle;
//            action.titleColor = KLColor(@"#323233");
            action.clickBlock = ^{
                !cancelAction ?: cancelAction();
            };
        })
        .LeeAddAction(^(LEEAction * _Nonnull action) {
            action.title = sureTitle;
            action.titleColor = kMainColor;
            action.clickBlock = ^{
                !sureAction ?: sureAction();
            };
        })
#ifdef __IPHONE_13_0
.LeeUserInterfaceStyle(UIUserInterfaceStyleLight)
#endif
        .LeeShow();
    } else {
        LEEAlert.alert.config
        .LeeTitle(title)
        .LeeContent(message)
        .LeeMaxWidth(280)
        .LeeAddAction(^(LEEAction * _Nonnull action) {
            action.title = cancelTitle?cancelTitle:sureTitle;
//            action.titleColor = JYColor_Main();
            action.clickBlock = ^{
                if (sureAction) {
                    !sureAction ?: sureAction();
                } else {
                    !cancelAction ?: cancelAction();
                }
            };
        })
#ifdef __IPHONE_13_0
.LeeUserInterfaceStyle(UIUserInterfaceStyleLight)
#endif
        .LeeShow();
    }
}


+ (void)showAlertTitle:(NSString *)title Message:(NSString *)message SureTitle:(NSString *)sureTitle SureAction:(void (^)(void))sureAction {
    LEEAlert.alert.config
    .LeeAddTitle(^(UILabel * _Nonnull label) {
        label.textColor = kMainColor;
        label.font = U_bfont(16);
        label.text = title;
    })
    .LeeContent(message)
    .LeeMaxWidth(280)
    .LeeAddAction(^(LEEAction * _Nonnull action) {
        action.type = LEEActionTypeCancel;
        action.title = SWString(@"Cancel");
        action.titleColor = [UIColor whiteColor];
//        action.backgroundColor = JYColor_Main();
        action.insets = UIEdgeInsetsMake(10, 40, 10, 40);
        action.cornerRadius = 20.0f;
        action.clickBlock = ^{
            if (sureAction) {
                !sureAction ?: sureAction();
            }
        };
    })
#ifdef __IPHONE_13_0
.LeeUserInterfaceStyle(UIUserInterfaceStyleLight)
#endif
    .LeeShow();
}

+(UIWindow *)searchKeyWindow
{
    UIWindow* window = nil;

    if (@available(iOS 13.0, *))
    {
       for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes)
       {
           if (windowScene.activationState == UISceneActivationStateForegroundActive)
           {
               window = windowScene.windows.firstObject;
               break;
           }
       }
    }else{
       window = [UIApplication sharedApplication].keyWindow;
    }
    return window;
}

+ (NSString *)localizedStringForKey:(NSString *)key Table:(NSString *)tab{
    
    NSString * currentlanguage = [UserDefaults fetchLanguage];
    if ([currentlanguage isEqualToString:@"1"]) {
        //中文
        currentlanguage = @"zh-Hans";
    }else if ([currentlanguage hasPrefix:@"2"]){
        //英语
        currentlanguage = @"en";
    }else if ([currentlanguage hasPrefix:@"3"]){
        //西班牙语
        currentlanguage = @"es";
    }else if ([currentlanguage hasPrefix:@"4"]){
        //俄罗斯语
        currentlanguage = @"ru";
    }else if ([currentlanguage hasPrefix:@"5"]){
        //韩语
        currentlanguage = @"ko";
    }else if ([currentlanguage hasPrefix:@"6"]){
        //日语
        currentlanguage = @"ja";
    }else if ([currentlanguage hasPrefix:@"7"]){
        //土耳其语
        currentlanguage = @"tr";
    }else if ([currentlanguage hasPrefix:@"8"]){
        //德语
        currentlanguage = @"de";
    }else if ([currentlanguage hasPrefix:@"9"]){
        //法语
        currentlanguage = @"fr";
    }else if ([currentlanguage hasPrefix:@"10"]){
        //yidaliyu
        currentlanguage = @"it";
    }else if ([currentlanguage hasPrefix:@"11"]){
        //葡萄牙
        currentlanguage = @"pt-pt";
    }else if ([currentlanguage hasPrefix:@"12"]){
        //拉丁语
        currentlanguage = @"la";
    }else{
        //中文
        currentlanguage = @"zh-Hans";
    }
    if (key.length > 0) {
        
        NSString *path = [[NSBundle mainBundle] pathForResource:currentlanguage
                                                             ofType:@"lproj"];
        NSBundle * _bundle = [NSBundle bundleWithPath:path];
    

        //第二个参数是语言包文件Language.strings的前缀
        NSString *result = NSLocalizedStringFromTableInBundle(key,
                                                              tab,
                                                              _bundle,
                                                              @"");
        return result;
        
    }else{
        NSString *path = [[NSBundle mainBundle] pathForResource:@"en"
                                                             ofType:@"lproj"];
        NSBundle * _bundle = [NSBundle bundleWithPath:path];
    

        //第二个参数是语言包文件Language.strings的前缀
        NSString *result = NSLocalizedStringFromTableInBundle(key,
                                                              tab,
                                                              _bundle,
                                                              @"");
        return result;
    }
    
}


+ (unsigned int)hexChangeToInt:(NSString *)hex {
    NSScanner *scanner = [NSScanner scannerWithString:hex];
    unsigned int decimal = 0;
    [scanner scanHexInt:&decimal];
    NSLog(@"16转10进制：%u", decimal);
    return decimal;
}

/*
 二进制转十进制
 
 @return 十进制字符串
 */
+ (NSString *)binaryToDecimal:(NSString *)string {
    int ll = 0 ;
    int  temp = 0 ;
    for (int i = 0; i < string.length; i ++) {
        temp = [[string substringWithRange:NSMakeRange(i, 1)] intValue];
        temp = temp * powf(2, string.length - i - 1);
        ll += temp;
    }
    NSString * result = [NSString stringWithFormat:@"%d",ll];
    return result;
}
/**
 十进制转二进制
 
 @return 二进制字符串
 */
+ (NSString *)decimalToBinary:(NSString *)string  {
    NSInteger num = [string integerValue];
    NSInteger remainder = 0;      //余数
    NSInteger divisor = 0;        //除数
    NSString * prepare = @"";
    
    while (true) {
        remainder = num%2;
        divisor = num/2;
        num = divisor;
        prepare = [prepare stringByAppendingFormat:@"%d",(int)remainder];
        
        if (divisor == 0) {
            break;
        }
    }
    
    NSString * result = @"";
    for (NSInteger i = prepare.length - 1; i >= 0; i --) {
        result = [result stringByAppendingFormat:@"%@",
                  [prepare substringWithRange:NSMakeRange(i , 1)]];
    }
    return [NSString stringWithFormat:@"%08d",[result intValue]];
}

#pragma mark 时间戳 转日期 （yyyy-MM-dd）
+ (NSString *)timeWithYearMonthDayCountDown:(NSString *)timestamp Format:(NSString *)format{
    NSTimeInterval timeInterval = [timestamp doubleValue];
    long a = [[[NSUserDefaults standardUserDefaults] valueForKey:@"secondFromGMT"] longLongValue];
    NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:timeInterval - a];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // 实例化一个NSDateFormatter对象，设定时间格式，这里可以设置成自己需要的格式
    // 强制所属地区
//    dateFormatter.timeZone = [NSTimeZone systemTimeZone];
//    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_Hans_CN"];
//    dateFormatter.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
    [dateFormatter setDateFormat:format];
    NSString *dateStr = [dateFormatter stringFromDate:detailDate];

    return dateStr;
}

+ (void)updateMACAddress:(NSString *)mac  ForUUID:(NSString *)uuid {
    if (mac && uuid) {
        [[NSUserDefaults standardUserDefaults] setValue:mac forKey:uuid];
    }
}
+ (NSString *)getAddressForUUID:(NSString *)uuid {
    NSString * ui = [[NSUserDefaults standardUserDefaults] valueForKey:uuid];
    return ui?:@"";
}

@end
